package guestbook

import (
	"github.com/labstack/echo"
	auth "tacitus/library/authorized"
	"tacitus/library/format"
	resp "tacitus/library/response"
	"time"
)

type PublicityComment struct {
	UserNickName string `json:"user_nick_name"`
	Content string `json:"content"`
	CreateTime int64 `json:"create_time"`
	CreateTimeStr string `json:"create_time_str"`
	ReplyUserNickName string `json:"reply_user_nick_name"`
	ReplyContent string `json:"reply_content"`
	ReplyTime int64 `json:"reply_time"`
	ReplyTimeStr string `json:"reply_time_str"`
}

// 显示公开的留言
func ShowPublicityCommentListHandler(c echo.Context) error {
	i := new(resp.PageFields)
	if err := c.Bind(i); err != nil {
		return err
	}
	data := make([]Guestbook, 0)
	count, err := x.Where("publicity != 0").OrderBy("create_time DESC").Limit(i.Size(), i.Offset()).FindAndCount(&data)
	if err != nil {
		return err
	}
	uis := make([]int64, 0)
	for _, item := range data {
		uis = append(uis, item.UserID, item.ReplyUserID)
	}
	um := make(map[int64]string)
	if err := u.MatchNickName(uis, &um); err != nil {
		return err
	}
	res := make([]PublicityComment, len(data))
	for index, item := range data {
		res[index] = PublicityComment{
			UserNickName:      um[item.UserID],
			Content:           item.Content,
			CreateTime:        item.CreateTime,
			CreateTimeStr:     format.DateTime(item.CreateTime),
			ReplyUserNickName: um[item.ReplyUserID],
			ReplyContent:      item.ReplyContent,
			ReplyTime:         item.ReplyTime,
			ReplyTimeStr:      format.DateTime(item.ReplyTime),
		}
	}
	return resp.Page(c, res, *i.SetItemCount(int(count)))
}

// 显示我的留言列表
func ShowMyCommentListHandler(c echo.Context) error {
	uid := auth.CurrentUser(c).UserID
	data := make([]Guestbook, 0)
	if err := x.Where("user_id = ?", uid).Find(&data); err != nil {
		return err
	}
	return resp.Data(c, data)
}

// 未登录状态添加留言，建议提交联系方式
func AddCommentInUnLoggedHandler(c echo.Context) error {
	i := new(struct {
		Content string `json:"content"`
		Contact string `json:"contact"`
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	co := &Guestbook{
		Content:      i.Content,
		Contact:      i.Contact,
		CreateTime:   time.Now().Unix(),
	}
	if _, err := x.Insert(co); err != nil {
		return err
	}
	return nil
}

// 已登录状态添加留言
func AddCommentInLoggedHandler(c echo.Context) error {
	uid := auth.CurrentUser(c).UserID
	i := new(struct {
		Content string `json:"content"`
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	co := &Guestbook{
		UserID:uid,
		Content:      i.Content,
		CreateTime:   time.Now().Unix(),
	}
	if _, err := x.Insert(co); err != nil {
		return err
	}
	return nil
}